package com.open.capacity.user.service.impl;


import com.open.capacity.commons.Result;
import com.open.capacity.user.dao.Sys3authDao;
import com.open.capacity.user.model.Sys3auth;
import com.open.capacity.user.service.Sys3authService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Slf4j
@Service
public class Sys3authServiceImpl implements Sys3authService {

    @Autowired
    private Sys3authDao authDao;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(Sys3auth auth) {
        auth.setUpdateTime(new Date());
        authDao.save(auth);
        log.info("保存三权：{}", auth);
    }


    @Override
    public Sys3auth find() {
        return authDao.find();
    }


    @Override
    public Result setAdmins(Sys3auth auth) throws Exception {
        int i = 0;

        if (StringUtils.isEmpty(auth.getAdmin1Userid())) {
            throw new Exception("请选择设置员！");
        }
        if (auth.getAdmin1Userid().split(",").length > 1) {
            throw new Exception("仅能配置一个设置员！");
        }
        if (StringUtils.isEmpty(auth.getAdmin2Userid())) {
            throw new Exception("'请选择审核员！'！");
        }
        if (auth.getAdmin2Userid().split(",").length > 1) {
            throw new Exception("'仅能配置一个审核员！'！");
        }
        if (StringUtils.isEmpty(auth.getAdmin3Userid())) {
            throw new Exception("'请选择审计员！'！");
        }
        if (auth.getAdmin3Userid().split(",").length > 1) {
            throw new Exception("'仅能配置一个审计员！'！");
        }
        if (auth.getAdmin1Userid().equals(auth.getAdmin2Userid()) || auth.getAdmin1Userid().equals(auth.getAdmin3Userid()) || auth.getAdmin2Userid().equals(auth.getAdmin3Userid())) {
            throw new Exception("''三个角色不能为同一个人！'！'！");
        }

        Sys3auth model = authDao.find();
        if (model != null) {
            auth.setUpdateTime(new Date());
            i = authDao.updateAdmin(auth);
        } else {
            i = authDao.save(auth);
        }

        return i > 0 ? Result.succeed("操作成功") : Result.failed("操作失败");
    }
}
